package atom.core3.hibernate;
/**
 * <p>Title: </p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2011.12</p>
 * @author 赵明才
 * @version 1.0
 */

import java.util.HashMap;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class MutiHibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    //private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    //private static String CONFIG_FILE_LOCATION_ORACLE = "/hibernate.oracle.cfg.xml";
	private final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  Configuration configuration = new Configuration();
    private org.hibernate.SessionFactory sessionFactory;
    private String configFile ;
    private static HashMap<String,String> configFilenameMap = new HashMap();
    private static HashMap<String,MutiHibernateSessionFactory> instanceMap= new HashMap();
    //ThreadLocal 很容易内存泄露
    private MutiHibernateSessionFactory() {
    }
	public static MutiHibernateSessionFactory getInstance (String key) {
		MutiHibernateSessionFactory instance;
		instance = instanceMap.get(key);
		if (null == instance) 
		{
			instance = new MutiHibernateSessionFactory();
			String configfile = configFilenameMap.get(key);
			instance.configFile = configfile;
		
			instanceMap.put(key, instance);
		}
		return instance;
	}
	public static void setConfigFilenameMap(String key,String configfile)
	{
		configFilenameMap.put(key, configfile);
	}
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }
    //这种方法得到的Session，需要自己管理
    public  Session getNewSession() throws HibernateException {
		if (sessionFactory == null) 
		{
			rebuildSessionFactory();
		}
		Session session = (sessionFactory != null) ? sessionFactory.openSession()
				: null;
		
		return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}


	/**
     *  return hibernate configuration
     *
     */
	public Configuration getConfiguration() {
		return configuration;
	}
	public ThreadLocal getThreadLocal()
	{
		return threadLocal;
	}
	public void showThreadLocal()
	{
		
	}
}
